<script lang="ts" setup>
import { message } from 'ant-design-vue';
defineProps<{
  current: number
}>()
// 修改父组件数据
const emits = defineEmits<{
  (e: 'update:current', value: number): void
  (e: 'update:image', value: File): void
  (e: 'complete'): void
}>()

// 上一步
function handlePrev() {
  emits('update:current', 1)
}

// 执行父组件创建课程方法
function handleComplete() {
  if (!imageSrc) {
    message.warn('请先上传缩略图')
    return
  }
  emits('complete')
}

// 图片文件初始参数
let image = ref<File>()
let imageSrc = ref<string>('')
const fileUpload = ref<HTMLInputElement>()

// 监听获取到图片文件，转成base64格式
watch(() => image.value, async () => {
  if (!image.value) return ''
  // 获取图片二进制数据传入transformArrayBufferToBase64
  const b = transformArrayBufferToBase64(await image.value.arrayBuffer())
  imageSrc.value = `data:${image.value.type};base64,${b}`
  emits('update:image', image.value)
})

// 上传图片
function handleImageUpload(e: Event) {
  const target = e.target as HTMLInputElement
  const file = target.files?.[0]
  if (!file) return
  image.value = file
}

// 图片二进制数据转成base64
function transformArrayBufferToBase64(buffer: ArrayBuffer) {
  var binary = '';
  // 使用Uint8Array类型的bytes数组来遍历buffer中的每一个字节，并将字节转换为字符，拼接到binary字符串中
  var bytes = new Uint8Array(buffer);
  for (var len = bytes.byteLength, i = 0; i < len; i++) {
    // String.fromCharCode()将字节转换为字符:65=>A
    binary += String.fromCharCode(bytes[i]);
  }
  // window.btoa()方法将binary字符串转换为Base64编码字符串
  return window.btoa(binary);
}

</script>

<template>
  <div w-full>
    <div flex="~ col center">
      <input ref="fileUpload" type="file" hidden @change="handleImageUpload" />
      <span text="5" font-bold mb-8>上传缩略图</span>
      <div b w-80 h-40 flex="~ center" cursor-pointer @click="fileUpload?.click()">
        <img v-if="image" :src="imageSrc" w-full h-full />
        <cloud-upload-outlined v-else text="15" />
      </div>
    </div>
    <div flex justify-end gap-2>
      <a-button @click="handlePrev" style="background-color:#1677ff">上一步</a-button>
      <a-button type="primary" @click="handleComplete" style="background-color:#1677ff">完成</a-button>
    </div>
  </div>
</template>